package com.jec.module;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.jec.Bootstrap;
import com.jec.utils.Response;

import lombok.Data;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping(value = "/name")
@Log4j
public class NameController {
	
	private Properties nameProperties = null;
	
    @PostConstruct
    public void init(){
    	
		File configFile = getConfigFile();
		
		log.info("Loading: " + configFile.getAbsolutePath());
		
		Properties properties = new Properties();
		
		if(configFile.exists() && configFile.isFile()) {
			try {
				FileInputStream fis = new FileInputStream(configFile);
				InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
				properties.load(isr);
			} catch(Exception e) {
				log.warn("Load names failed.", e);
			}
		}
		
		nameProperties = properties;
    }

	
	private File getConfigFile() {
		
		String path = Bootstrap.getApplicationPath();
		
		String filename = path + File.separatorChar + "name.properties";
		
		File configFile = new File(filename);
		
		return configFile;
	}
	
	
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody
    Response index(){
    	
    	List<Entry> list = Lists.newLinkedList();
    	if(nameProperties == null) {
    		return Response.Builder(list);	
    	}
    	
    	for(String s : nameProperties.stringPropertyNames()) {
    		Entry e = new Entry();
    		e.setCode(s);
    		e.setName(nameProperties.getProperty(s));
    		list.add(e);
    	}

        return Response.Builder(list);
    }
    
    @RequestMapping(value = "add/{code}/{name}", method = RequestMethod.GET)
    public @ResponseBody
    Response add(@PathVariable(value = "code") String code,
    		@PathVariable(value = "name") String name){
    	
    	if(nameProperties == null) {
    		
    		nameProperties = new Properties();
    		
    	}
    	
    	nameProperties.setProperty(code, name);
    	
    	try {
    	
	    	FileWriter fw = new FileWriter(this.getConfigFile());
	    	
	    	nameProperties.store(fw, "Code and name map file");
    	
    	} catch(Exception e) {
    		
    	}

        return Response.Builder();
    }
    
    @Data
    public static class Entry {
    	private String code;
    	private String name;
    }
	
}
